function qs(data) {
  return JSON.parse(JSON.stringify(data))
}

var state = 0
var sucTxt = 'success'
var loadTxt = 'load'
var imgUrls = ['wifi', 'search', sucTxt, 'warning', 'out', 'error', 'bg']
var warningTxt = ''
var step = 0
var resultTxt = ''
var stepData = qs(networkStep)

var timer = null
var outState = false // 超时状态
var networkOutTxt = '网络检测异常'
var resultState = false

var networkState = 0

if (queryObj.systemOff == '1' && isAndroid) {
  networkState = 2
} else if (queryObj.systemOff == '1' && isIOS) {
  networkState = 1
}
var errorTxt = networkTxt[networkState]
// console.log(networkState, 'networkState===')
function resetData() {
  state = 0
  warningTxt = ''
  step = 0
  resultTxt = ''
  stepData = qs(networkStep)
  errorTxt = networkTxt[networkState]
  timer = null
  resultState = false
}

function isShowTell() {
  $id('tell').style.display = state != 1 ? 'block' : 'none'
}

function isShowReminder() {
  $id('reminder').style.display = !state ? 'block' : 'none'
}

function isShowResultTxt() {
  $id('resultTxt').innerHTML = resultTxt
  $id('resultTxt').style.display = state === 2 ? 'block' : 'none'
}

function checkImgState() {
  var imgStateUrl = imgUrls[state]
  if (resultState) {
    imgStateUrl = imgUrls[4]
  }
  // console.log(imgStateUrl, resultState, 'imgStateUrl==')
  $id('network-logo').innerHTML = '<img src="./static/images/network-' + imgStateUrl + '.png" class="network-logo" >'
}

function isShowBtn() {
  var txt = '重新检测'
  if (!state) {
    txt = '开始检测'
    outState = false
  }
  if (state == 1) {
    txt = ''
    CaH5.track('recheck', {})
  }
  $id('btn').innerHTML = txt
  $id('btn').style.display = state !== 1 ? 'block' : 'none'
  $id('jcsm').style.display = state === 0 ? 'block' : 'none'
}

function isShowError() {
  var dom = $id('error')
  if (state === 4 || state === 5 || warningTxt === networkOutTxt) {
    var html = ''
    errorTxt.map(function (item, idx) {
      var itemTxt = '<div><div style="' + (idx ? '' : 'padding: 20px 0px;') + '">'
      item.map(function (children) {
        itemTxt += '<p>' + children + '</p>'
      })
      itemTxt += '</div></div>'
      html += itemTxt
    })
    $id('network-reminder').innerHTML = html
    dom.style.display = 'block'
  } else {
    dom.style.display = 'none'
  }
}


function networkHtml() {
  var color = ''
  var txt = stateTxt[state]
  if (state == 5) {
    color = 'txt-up'
  }
  if (state == 3 || state == 4) {
    color = 'txt-warning'
  }
  if (state == 3 || state == 5) {
    txt = warningTxt
  }
  if (state == 4) {
    txt = '当前网络服务已断开'
  }
  $id('networkHtml').innerHTML = '<span class="' + color + '">' + txt + '</span>'
}

function startCheck() {
  if (state === 0) {
    state = 1
    getNetworkList()
  } else {
    state = 0
    if (!CUR_SUCCESS_URL) {
      networkUrlIdx = Math.floor(Math.random() * urls.length)
      timeoutDate = (urls.length - networkUrlIdx) * dateTiem
    }
    resetData()
    refreshDom()
  }
}

function stepState(idx, state) {
  stepData[idx].state = state
}

function successHandle(res) {
  console.log(res)
  var data = res.body.checkStatus
  // 获取检测策略完成， data=0检测结果，data=1返回检测策略
  // console.log(data, step, '状态的')
  if (data == 1 && step === 0) {
    // 改变步骤条的状态
    stepState(0, sucTxt)
    stepState(1, loadTxt)
    step += 1
    checkNetwork(res)
  } else if (data == 1 && step === 1) {
    stepData.push(qs(sdNetworkStep[0]), qs(sdNetworkStep[1]))
    stepState(1, sucTxt)
    stepState(2, sucTxt)
    stepState(3, loadTxt)
    step += 1
    checkNetwork(res)
  } else {
    // console.log(data, step, '状态的进来了')
    if (step == '2') {
      stepState(3, sucTxt)
      stepState(step + 2, sucTxt)
    } else {
      stepState(1, sucTxt)
      stepState(2, sucTxt)
    }
    state = 2
    resultTxt = decodeURIComponent((res.body.checkAnalyse && res.body.checkAnalyse.checkText) || '')
    resultState = res.body.checkAnalyse.checkScore < 60 ? true : false
  }
  refreshDom()
  // console.log(state, 'success====')
  timer = clearTimeout(timer)
}

// 循环检测结果
function checkNetwork(res) {
  var idx = 0
  var list = res.body.checkStrategy.checkList
  var checkResults = []
  // 开始循环检测策略
  function checkNetworkItem() {
    var item = list[idx]
    stepData[step == 1 ? 1 : 3].subName = item.remark || ''
    var params = {
      cType: item.ctype,
      target: item.target,
      opt: item.opt
    }
    // console.log(params, 'params====检测参数', idx)
    zs.networkDiagnosis({
      params,
      success(result) {
        // console.log(result, 'res=networkDiagnosis')
        checkResults[idx] = {
          ctype: item.ctype,
          target: item.target,
          result: result.result
        }
        idx += 1
        // 当前策略返回结果，执行下一个策略检测
        if (list[idx]) {
          checkNetworkItem()
        } else {
          // 策略执行完毕提交所有策略检测结果
          var param = {
            checkVer: "1.0.0",
            checkRequest: {
              uuid: res.body.uuid,
              channel: (queryObj && queryObj.channel) || 'default',
              checkResults
            }
          }
          getNetworkList(param)
        }
        refreshDom()
      },
      fail(err) {
        console.log(err, 'err=networkDiagnosis')
        CaH5 && CaH5.error(err, 'checkNetworkFail')
        state = 3
        warningTxt = networkOutTxt
        errorTxt = networkTxt[isIOS ? 1 : 2]
        refreshDom()
      }
    })
  }
  checkNetworkItem()
}

function getNetworkList(params) {
  params && console.log('第二次获取')
  timer = clearTimeout(timer)
  refreshDom()
  if (!params) {
    timer = setTimeout(function() {
      state = 3
      outState = true
      warningTxt = '获取检测策略超时，请稍后重试'
      timer = clearTimeout(timer)
      refreshDom()
    }, timeoutDate * 1000)
  }
  var fail = function (err) {
    console.log(err, outState, '20000==')
    if (outState) {
      return false
    } else {
      outState = true
    }
    // 网络断开
    if (!err.code) {
      state = 4
      errorTxt = networkTxt[isIOS ? 1 : 2]
    } else if (err.code && String(err.code).substring(0, 1) == 2) {
      // 可重试
      state = 3
      warningTxt = params ? '获取分析结果异常，请稍后重试' : '获取检测策略异常，请稍后重试'
    } else {
      // 不可重试
      state = 5
      warningTxt = params ? '获取分析结果失败' : '获取检测策略失败'
      errorTxt = networkTxt[0]
    }
    refreshDom()
    timer = clearTimeout(timer)
    CaH5 && CaH5.error(err, 'resultFail')
  }
  var success = function (res) {
    // console.log(outState, 'outState====')
    if (outState) {
      return false
    }
    if (!res.code) {
      successHandle(res)
    } else {
      fail(res)
    }
  }
  getNetwork(params, success, fail)
}

function checkedStep() {
  if (state === 1) {
    var dom = ''
    stepData.map(function (item, idx) {
      var itemDom = '<div class="flex flex-align-center">'
      itemDom += '<img class="step-img" src="./static/images/step-' + item.state + '.png"></img>' + '<div class="flex-1 txt-left txt-info pd-l-sm txt-' + item.state + '"> ' + item.name + '</div></div>'
      if (idx != stepData.length - 1) {
        itemDom += '<div class="step-line p-r">'
        if (stepData[idx + 1].state != 'nostart') {
          itemDom += '<div class="line p-b"></div>'
        } else {
          itemDom += '<div class="line p-b line-no-start"></div>'
        }
        itemDom += '<div class="size12 txt-left txt-minor" style="padding-left: 24px">' + item.subName + '</div></div>'
      }
      dom += itemDom
    })
    $id('step').style.display = 'block'
    $id('step').innerHTML = dom
  } else {
    $id('step').style.display = 'none'
  }
}

function refreshDom() {
  checkImgState()
  isShowReminder()
  isShowTell()
  networkHtml()
  isShowResultTxt()
  isShowBtn()
  isShowError()
  checkedStep()
  isShowError()
}

refreshDom()
